package com.bbcare.followup.plat.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.HuamitechApiUtil;
import com.bbcare.nutritious.plat.entity.PtHuamiToken;
import com.bbcare.nutritious.plat.service.IActivityHuamiService;
import com.bbcare.nutritious.plat.store.ibatis.IActivityHuamiDao;

/**
 * 
 * @name:         PtSynchHuamiDataTask.java
 * @author:       tao
 * @createTime:   2017年11月15日
 * @description:  华米手环数据同步任务  每天同步前一天的数据  步数、睡眠、心跳
 * @modify:
 *
 */

public class PtSynchHuamiDataTask implements Job{

    private final Log logger = LogFactory.getLog(PtSynchHuamiDataTask.class);
    
    @Autowired
    private IActivityHuamiService activityHuamiService;
    
    @Autowired
    private IActivityHuamiDao activityHuamiDao;

    @Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
        logger.info("---start: PtSynchHuamiDataTask---");
        long start = System.currentTimeMillis();
        Map<String,Object> param = new HashMap<String,Object>();
        try {
        	String activityStartDate = "";
        	String sleepStartDate="";
        	String heartStartDate="";
            String endDate = DateUtil.getDate_8(DateUtil.subDay(new Date(),1));
            
            String recordActivityRecord =""; //先删除最后一天记录
            String recordSleepRecord =""; //先删除最后一天记录
        	//查询需要同步数据的租户或队列
            param.put("status",Constants.COMMON_STATUS_NOMAL);
			List<Map<String,Object>> rules = activityHuamiDao.selectActiveRuleList(param);
			if(!CollectionUtils.isEmpty(rules)){
				for(int i =0;i<rules.size();i++){
					Map<String,Object> tokenParam = new HashMap<String,Object>();
					List<String> queueIdArray = new ArrayList<String>();
					queueIdArray.add(String.valueOf(rules.get(i).get("queue_id")));
					
					tokenParam.put("queueIdIn",queueIdArray);
					tokenParam.put("userStatus",Constants.QUEUE_STATUS_NOMAL);
					tokenParam.put("status",Constants.COMMON_STATUS_NOMAL);
					tokenParam.put("tenantId",rules.get(i).get("tenant_id"));
					List<PtHuamiToken> tokenList = activityHuamiDao.selectPtHuamiTokenList(tokenParam);
					
					if(!CollectionUtils.isEmpty(tokenList)){
						PtHuamiToken token = null;
						Map<String,Object> synchParam = new HashMap<String,Object>();
						for(int j = 0;j<tokenList.size();j++){
							//单个用户数据同步失败 不影响其他用户继续同步
							try{
								token = tokenList.get(j);
								//查询上次同步的最后时间
								synchParam.clear();
								synchParam.put("userId",token.getUserId());
								synchParam.put("tenantId",token.getTenantId());
								
								Map<String,Object> activiMap= activityHuamiDao.selectActivitiesLastDate(synchParam);
								Map<String,Object> sleepMap = activityHuamiDao.selectSleepLastDate(synchParam);
								
								//如果之前都未同步到数据  可能是第一次同步 或者 用户数据很多天后才同步到 华米平台 此时 按授权时间作为开始时间
								if(activiMap==null){
									activityStartDate = DateUtil.getDate_8(DateUtil.getDate_8(token.getCreateTime()));
								}else{
									activityStartDate = activiMap.get("testDate").toString();
									recordActivityRecord= activiMap.get("id").toString();
								}
								if(sleepMap==null){
									sleepStartDate = DateUtil.getDate_8(DateUtil.getDate_8(token.getCreateTime()));
								}else{
									sleepStartDate = sleepMap.get("testDate").toString();
									recordSleepRecord = sleepMap.get("id").toString();
								}
								
								heartStartDate=activityHuamiDao.selectHeartratesLastDate(synchParam);
								if(StringUtils.isBlank(heartStartDate)){
									heartStartDate = DateUtil.getDate_8(DateUtil.getDate_8(token.getCreateTime()));
								}
								
								//同步步数
								synchParam.clear();
								synchParam.put("recordId", recordActivityRecord);
								synchParam.put("id", token.getId());
								synchParam.put("accessToken",token.getAccessToken());
								synchParam.put("userId",token.getUserId());
								synchParam.put("tenantId",token.getTenantId());
//								synchParam.put("startDate",DateUtil.getDate_8(DateUtil.addDay(DateUtil.getDate_8(activityStartDate),1)));
								synchParam.put("startDate",activityStartDate);
								synchParam.put("endDate",endDate);
								synchParam.put("interval",HuamitechApiUtil.INTERVAL_DAY);
								synchParam.put("refreshToken",token.getRefreshToken());
								activityHuamiService.synchActivities(synchParam);
								
								//同步睡眠时间
//								synchParam.put("startDate",DateUtil.getDate_8(DateUtil.addDay(DateUtil.getDate_8(sleepStartDate),1)));
								synchParam.put("startDate",sleepStartDate);
								synchParam.put("recordId", recordSleepRecord);
								activityHuamiService.synchSleep(synchParam);
								
								//同步心率
								synchParam.put("startDate",DateUtil.getDate_8(DateUtil.addDay(DateUtil.getDate_8(heartStartDate),1)));
//								activityHuamiService.synchHeartrates(synchParam);
								
							}catch(Exception e){
								logger.error("用户["+token.getUserId()+"]数据同步手环运动数据失败",e);
							}
						}
					}
				}
				
			}
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			logger.error("PtSynchHuamiDataTask error ",e);
		}
        
        long end = System.currentTimeMillis() ;
        logger.info("---end: PtSynchHuamiDataTask---耗时:" +(end-start)+"毫秒");
        return;
    }

}
